package com.itbaizhan;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/*通过HttpSession实现客户端与服务端会话的维持
需求：当客户端浏览器第一次访问Servlet时响应“您好，欢迎您第一次访问！”，第二次访问时响应“欢迎您回来！”。*/
public class WelcomeSession extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //将HttpSession对象设置false,没有HttpSession对象时拿不到session
        HttpSession session = req.getSession(false);

        boolean flag = true;
        if(session == null){
            flag = false;
            //获得session
           // req.getSession();
            req.getSession(true);
        }
        resp.setContentType("text/plain;charset=utf-8");
        PrintWriter pw =resp.getWriter();
        if(flag){
            pw.println("欢迎你回来");
        }else {
            pw.println("你好，欢迎你第一次访问");
        }
        pw.flush();
        pw.close();
    }
}
